package com.jie.algorithm.thrid.eventbus;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by ZDST-03 on 2018/2/6.
 * EventBus管理器，对EventBus进行基本封装
 */

public class EventBusManager {

    private static EventBusManager instance = null;
    private final EventBus eventBus;

    private EventBusManager(){
        eventBus = EventBus.getDefault();
    }

    public static EventBusManager getInstance() {
        if (instance == null){
            synchronized (EventBusManager.class){
                instance = new EventBusManager();
            }
        }
        return instance;
    }

    public void register(Object object){
        if (!eventBus.isRegistered(object)) {
            eventBus.register(object);
        }
    }

    public void unRegister(Object object){
        if (eventBus.isRegistered(object)) {
            eventBus.unregister(object);
        }
    }

    /**
     * 发生一般事件
     * @param object 传递对象
     */
    public void post(Object object){
        eventBus.post(object);
    }

    /**
     * 发生一般事件
     * @param code 事件码
     */
    public void sendEvent(@EventConstant int code){
        sendEvent(new Event(code));
    }

    /**
     * 发送一般事件
     * @param event
     */
    public <T extends Event>  void sendEvent(T event){
        eventBus.post(event);
    }

    /**
     * 发送粘性事件，即自己触发的事件，自己也能接收处理
     * @param event
     */
    public <T extends Event> void sendStickyEvent(T event){
        eventBus.postSticky(event);
    }
}
